package org.geeks.gsflyingsaucer.controller;

import com.lowagie.text.pdf.BaseFont;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

@RestController
@Slf4j
public class HelloController {

  @GetMapping("hello")
  public void hello(HttpServletResponse response) throws Exception {
    final TemplateEngine templateEngine = new TemplateEngine();

    final Context context = new Context();
    context.setLocale(Locale.SIMPLIFIED_CHINESE);
    context.setVariable("username", "宋骁");

    ClassLoaderTemplateResolver fileTemplateResolver = new ClassLoaderTemplateResolver();

    templateEngine.setTemplateResolver(fileTemplateResolver);

    String result = templateEngine.process("/templates/hello.html", context);

    log.info("HTML content is {}", result);

    ITextRenderer renderer = new ITextRenderer();

    ITextFontResolver iTextFontResolver = renderer.getFontResolver();

    iTextFontResolver.addFont("/fonts/simsun.ttf", BaseFont.IDENTITY_H, false);

    renderer.getSharedContext().setMedia("pdf");

    renderer.setDocumentFromString(result);

    renderer.layout();

    renderer.createPDF(response.getOutputStream());
  }
}
